package org.divineryang.service.impl;

import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.divineryang.exception.NewBeeException;
import org.divineryang.mapper.SysRoleUserMapper;
import org.divineryang.mapper.SysUserMapper;
import org.divineryang.model.dto.system.AssginRoleDto;
import org.divineryang.model.dto.system.LoginDto;
import org.divineryang.model.dto.system.SysUserDto;
import org.divineryang.model.entity.system.SysUser;
import org.divineryang.model.vo.common.ResultCodeEnum;
import org.divineryang.model.vo.system.LoginVo;
import org.divineryang.service.SysUserService;
import org.divineryang.utils.KeyUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;


import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @program new-bee
 * @Description
 * @Author Diviner Yang
 * @Date 2024/04/18 15:03
 * @Version 1.0
 */
@Service
public class SysUserServiceImpl implements SysUserService {
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private SysRoleUserMapper sysRoleUserMapper;

    @Autowired
    private RedisTemplate<String , String> redisTemplate ;

    @Override
    public LoginVo login(LoginDto loginDto) {
        String codeKey = loginDto.getCodeKey();
        String captcha = loginDto.getCaptcha();

        String redisCode = redisTemplate.opsForValue().get(KeyUtils.CAPTCHA_KEY + codeKey);
        if (StrUtil.isEmpty(redisCode) || !StrUtil.equalsIgnoreCase(captcha,redisCode)){
            throw new NewBeeException(ResultCodeEnum.VALIDATECODE_ERROR);
        }

        redisTemplate.delete(KeyUtils.CAPTCHA_KEY + codeKey);

        SysUser sysUser = sysUserMapper.selectByUserName(loginDto.getUserName());
        if(sysUser == null) {
            throw new RuntimeException("用户名或者密码错误") ;
        }
        // 验证密码是否正确
        String inputPassword = loginDto.getPassword();
        String md5InputPassword = DigestUtils.md5DigestAsHex(inputPassword.getBytes());
        if(!md5InputPassword.equals(sysUser.getPassword())) {
            throw new NewBeeException(ResultCodeEnum.LOGIN_ERROR);
        }
        // 生成令牌，保存数据到Redis中
        String token = UUID.randomUUID().toString().replace("-", "");
        redisTemplate.opsForValue().set(KeyUtils.USER_LOGIN_KEY + token , JSON.toJSONString(sysUser) , 30 , TimeUnit.MINUTES);
        // 构建响应结果对象
        LoginVo loginVo = new LoginVo() ;
        loginVo.setToken(token);
        loginVo.setRefresh_token("");
        // 返回
        return loginVo;
    }

    @Override
    public SysUser getUserInfo(String token) {
        String redisToken = redisTemplate.opsForValue().get(KeyUtils.USER_LOGIN_KEY + token);
        SysUser sysUser = JSON.parseObject(redisToken, SysUser.class);
        return sysUser;
    }

    @Override
    public void logout(String token) {
        redisTemplate.delete(KeyUtils.USER_LOGIN_KEY + token);
    }

    @Override
    public void saveSysUser(SysUser sysUser) {
        SysUser dbSysUser = sysUserMapper.selectByUserName(sysUser.getUserName());
        if (dbSysUser!=null){
            throw new NewBeeException(ResultCodeEnum.USER_NAME_IS_EXISTS);
        }
        String md5_password = DigestUtils.md5DigestAsHex(sysUser.getPassword().getBytes());
        sysUser.setPassword(md5_password);
        sysUser.setStatus(1);
        sysUserMapper.saveSysUser(sysUser) ;
    }

    @Override
    public void updateSysUser(SysUser sysUser) {
        sysUserMapper.updateSysUser(sysUser);
    }

    @Override
    public void deleteById(Long userId) {
        sysUserMapper.deleteById(userId);
    }

    @Override
    public PageInfo<SysUser> findByPage(SysUserDto sysUserDto, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum,pageSize);
        List<SysUser> sysUserList=sysUserMapper.findByPage(sysUserDto);
        PageInfo<SysUser> pageInfo = new PageInfo<>(sysUserList);
        return pageInfo;
    }

    @Override
    public void doAssign(AssginRoleDto assginRoleDto) {
        // 删除之前的所有的用户所对应的角色数据
        sysRoleUserMapper.deleteByUserId(assginRoleDto.getUserId()) ;

        // 分配新的角色数据
        List<Long> roleIdList = assginRoleDto.getRoleIdList();
        roleIdList.forEach(roleId-> sysRoleUserMapper.dodoAssign(assginRoleDto.getUserId(),roleId));
    }
}